//
//  HKToastView.m
//  HKTimeKitApp
//
//  Created by huzhaoke1 on 2023/5/19.
//

#import "HKToastView.h"
#import "NSString+boundRect.h"
#import "UIView+KSShow.h"
#import "HKCommonDefine.h"
#import "UIView+properties.h"

#define kToastShowTime  1.5 //toast 显示时间，默认1.5秒
#define kVerticalPadding 9
#define kHorizonPadding 23

@interface HKToastView ()

@property (nonatomic, strong) UILabel* titleLabel;

@end

@implementation HKToastView

+ (HKToastView *)sharedToastView
{
    static HKToastView *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[HKToastView alloc] init];
    });
    return instance;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self addSubview:self.titleLabel];
    }
    return self;
}

- (void)showToast:(NSString *)title {
    [self showToast:title duration:kToastShowTime];
}

- (void)showToast:(NSString *)title
         duration:(CGFloat)duration {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (self.superview == window || ![title isKindOfClass:NSString.class]) {
        return;
    }
    self.titleLabel.text = title;
    CGSize textSize = [title ks_sizeWithFont:self.titleLabel.font];
    CGRect bounds = CGRectMake(0, 0, ceilf(textSize.width) + 2*kHorizonPadding, ceilf(textSize.height)+2*kVerticalPadding);
    
    
    CGSize screenSize = HKKeyWindow.bounds.size;
    self.frame = CGRectMake(0, 0, HKKeyWindow.width, HKKeyWindow.height);
    
    CGFloat left = (screenSize.width-bounds.size.width)/2;
    CGFloat top = (screenSize.height-bounds.size.height)/2;
    self.titleLabel.frame = CGRectMake(left, top, bounds.size.width, bounds.size.height);
        [HKKeyWindow addSubview:self];
    WS
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        SS
        [self dismissLoading];
    });
}

- (void)dismissLoading
{
    [self removeFromSuperview];
}

#pragma mark - getter & setter
- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _titleLabel.font = [UIFont systemFontOfSize:16.0];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.backgroundColor = UIColorFromRGBA(0x000000, 0.4);
        _titleLabel.numberOfLines = 0;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.layer.cornerRadius = 6;
        _titleLabel.layer.masksToBounds = YES;
    }
    return _titleLabel;
}


@end
